import axios from 'axios'
import {closeLoading, openLoading} from "@/core/util/loading";
import {errorMsg, warningMsg} from "@/core/util/message";
import router from "@/core/router/router";

export const $http = axios.create({
    timeout: 100 * 1000,
});

const loading = (config: any) => {
    if (config.data && config.data.closeLoading) {
        return;
    }
    openLoading();
};

// 请求拦截  设置统一header
$http.interceptors.request.use(config => {
    loading(config);

    // this.queryParam.closeLoading
    let url: any = config.url;
    let haveHttp = (url + "").indexOf("http://").toString() != "-1";
    let haveHttps = (url + "").indexOf("https://").toString() != "-1";

    // config.headers['Token'] = getToken();
    // config.headers['adminHtmlVersion'] = getHtmlVersion();
    // config.headers['adminApiVersion'] = getApiVersion();
    // showLoading(null);
    if (haveHttp || haveHttps) {
    } else {
        config.url = process.env.VUE_APP_API_BASE_URL + url;
    }
    return config;
}, error => {
    return Promise.reject(error)
});

$http.interceptors.response.use(response => {
    //处理blob数据
    if (response.config.responseType && response.config.responseType == "blob") {
        closeLoading();
        return response;
    }

    let data: any = response.data;
    //请求成功
    if (data.code.toString() == "200") {
    }
    //请求失败
    else if (data.code.toString() == "500") {
        errorMsg(data.message)
    }
        // 咱也不知道啥原因
    // 就是想让用户重新登录
    else if (data.code.toString() == "555") {
        warningMsg("登录状态已失效，请重新登录");
        router.push({path: "/login"});
    }
    //请求失败
    else if (data.code.toString() == "400") {
        errorMsg(data.message)
    }
    //权限不足
    else if (data.code.toString() == "403") {
        errorMsg(data.message);
        router.push({path: "/error/403"});
    }
    //管理端登录失效
    else if (data.code.toString() == "401") {
        errorMsg("登录已失效，请重新登录.");
        router.push({path: "/login"});
    }
    //延迟关闭动画
    setTimeout(() => {
        closeLoading();
    }, 100);
    return data;
}, error => {
    closeLoading();
});

export default $http

